#!/bin/sh
set -x
DEPLOY_DIR="/data/skiff-deploy/CUST163-geely"
TOOL_DIR="/data/skiff-deploy/CUST163-geely"
PYTHON="$TOOL_DIR/tools/ansible/bin/python"
ANSIBLE="$TOOL_DIR/tools/ansible/bin/ansible-playbook"

HOSTS_SKIFF_BASE="$DEPLOY_DIR/apm/envs/hosts"
PLAYBOOK="$DEPLOY_DIR/apm/playbooks"
DEPLOY_LOG_DIR="../log/deploy/apm/"

DEFAULT_ACTION="deploy"
RUN_ACTION=$1
if [[ x"$RUN_ACTION" == x ]]; then
    RUN_ACTION=${DEFAULT_ACTION}
fi

# 手动设置 action 时，只允许 deploy 和 destroy
if [[ ${RUN_ACTION} != "deploy" ]] && [[ ${RUN_ACTION} != "destroy" ]]; then
    echo "Invailed run action, valied sail action is deploy or destroy"
    exit 2
fi

# 执行 destroy 时，需要用户再次确认
#if [[ ${RUN_ACTION} == "destroy" ]]; then
#    read -p "Are you sure you want to continue destroy (yes/no)?: " DOUBLE_CHECK
#    if [[ ${DOUBLE_CHECK} != "yes" ]]; then
#        exit 0
#    fi
#fi

check_ret() {
    ret=$1
    local env=$3
    if [[ ${ret} -ne 0 ]]; then
        echo "当前步骤执行异常,请修复后继续执行"
        exit 9
    elif [[ "$env"X == "X" ]]; then
        if [[ ${RUN_ACTION} == "deploy" ]];then
            touch ${DEPLOY_LOG_DIR}/$2
        fi
    else
        if [[ ${RUN_ACTION} == "deploy" ]];then
            touch ${DEPLOY_LOG_DIR}/${env}/$2
        fi
    fi
}

run() {
    date
    task=$1
    status_file=$(echo $task|awk -F'/' '{print $1"~"$2}')

    if [[ -f ${DEPLOY_LOG_DIR}/${status_file} ]]; then
       if [[ ${RUN_ACTION} == "deploy" ]];then
           echo "skip: $task"
       else
           # 后续优化逻辑
           rm -rf ${DEPLOY_LOG_DIR}/${status_file}

           ${PYTHON} ${ANSIBLE} -i ${HOSTS_SKIFF_BASE} ${PLAYBOOK}/${task} --skip-tags="remove_apm,chart_upgrade" -e sail_action=${RUN_ACTION}
           check_ret $? ${status_file}
       fi
    else
        ${PYTHON} ${ANSIBLE} -i ${HOSTS_SKIFF_BASE} ${PLAYBOOK}/${task} --skip-tags="remove_apm,chart_upgrade" -e sail_action=${RUN_ACTION}

        check_ret $? ${status_file}
    fi
}

deploy_init() {
    echo "初始化部署环境，需要/data目录大于30G的存储空间"
    echo "================================================================="
    mkdir -p ${DEPLOY_LOG_DIR}
}

deploy_apm() {
    echo "部署轻舟产品: apm"
    echo "================================================================="

    run apm.yml

    run apm-qatest.yml


}

main() {
    deploy_init
    deploy_apm
}
main;

echo "done!"
